/**
  ******************************************************************************
  * @file    timer.c 
  * @author  Aizbot
  * @brief   xxx.
  ******************************************************************************
  * @attention
  *
  * <h2><center>&copy; Copyright (c) 2023 Aizbot.
  * All rights reserved.</center></h2>
  *
  * http://www.aizbot.com
  *
  ******************************************************************************
  */

/* Includes ------------------------------------------------------------------*/
#include "timer.h"
#include "system.h"

/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/* Private functions ---------------------------------------------------------*/

/**
  * @brief  xxx.
  * @param  None
  * @retval None
  */
void Timer_Set(TIMER_t *timer, uint32_t nms)
{
	timer->current_time = HAL_GetTick();
	timer->expired_time = nms;
	timer->free_flag = 1;
}

/**
  * @brief  xxx.
  * @param  None
  * @retval None
  */
void Timer_Free(TIMER_t *timer)
{
	timer->free_flag = 0;
}

/**
  * @brief  Waitting for delay timeout.
  * @param  Init in the function TimeOutSet()
  * @retval None
  */
uint8_t Timer_Out(TIMER_t *timer)
{
	if(timer->free_flag)
	{
#if 1
		if ((HAL_GetTick() - timer->current_time) >= timer->expired_time)
#else
		if(HAL_GetTick() -(timer->expired_time + timer->current_time) < INT32_MAX)
#endif
		{
			return 1;
		}
	}
	return 0;
}

/**
  * @brief  xxx.
  * @param  None
  * @retval None
  */
void Timer_DelayMs(uint32_t nms)
{
	TIMER_t wait_timer;
	Timer_Set(&(wait_timer), nms);
	while(!Timer_Out(&wait_timer));
}

/**
  * @brief  xxx.
  * @param  None
  * @retval None
  */
void Timer_Start(TIMER_t *timer)
{
	timer->current_time = HAL_GetTick();
}

/**
  * @brief  xxx.
  * @param  None
  * @retval None
  */
void Timer_Stop(TIMER_t *timer)
{
	timer->expired_time = HAL_GetTick() - timer->current_time;
}

/**
  * @brief  xxx.
  * @param  None
  * @retval None
  */
void Timer_Test(void)
{
	static TIMER_t testTimer;
	static uint8_t testState = 0;
	
	switch(testState)
	{
	case 0:
		testState = 1;
		Timer_Start(&testTimer);
		break;

	case 1:
		testState = 0;
		Timer_Stop(&testTimer);
		break;
	}
//	Timer_DelayMs(5);
}

/************************ (C) COPYRIGHT Aizbot ********************************/
